/*
 * @Date: 2025-06-27 15:05:25
 * @Auth: 463997479@qq.com
 * @LastEditors: 463997479@qq.com
 * @LastEditTime: 2025-06-27 19:09:25
 * @FilePath: \corpus\src\pages\User\YkzQrcode\hooks\index.ts
 */
import { loginByAuthCode } from '@/services/ant-design-pro/api';
import { history, useModel } from '@umijs/max';
import { message } from 'antd';
import { useCallback, useEffect, useState } from 'react';
import { flushSync } from 'react-dom';

export default () => {
  const [timestamp, setTimestamp] = useState(new Date().getTime());
  const { initialState, setInitialState } = useModel('@@initialState');

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };
  const loginMode = {
    loginMode: 'YUKZ',
    appCode: 'portal',
    appName: '数据门户',
    icon: null,
    cover: null,
    appId: 'sdsjj-ggzyglxt_dingoa',
    redirectUrl: 'http://23.211.43.26/',
    title: null,
  };
  const onLogin = useCallback(async (event: any) => {
    const { data } = event;
    if (data.hasOwnProperty('code')) {
      const { code } = data;
      const res: any = await loginByAuthCode({
        code: code,
        loginMode: '2',
      });

      if (res.success === true) {
        message.success('登录成功！');
        await fetchUserInfo();
        const urlParams = new URL(window.location.href).searchParams;
        history.push(urlParams.get('redirect') || '/');
        return;
      }

      if (!res.success) {
        message.error('登录失败');
        window.location.reload();
        setTimestamp(new Date().getTime());
      }
    }
  }, []);

  useEffect(() => {
    window.addEventListener('message', onLogin);
    return () => {
      window.removeEventListener('message', onLogin);
    };
  }, []);

  return {
    loginMode,
    timestamp,
  };
};
